<template>
  <div class="container">
    <form validate @submit.stop.prevent="submit">
      <md-input-container>
        <label>用户名</label>
        <md-input name="username" required v-model="username" type="text"></md-input>
        <span class="md-error">用户名不能为空</span>
      </md-input-container>
      <md-input-container md-has-password>
        <label>密码</label>
        <md-input name="username" required v-model="password" type="username"></md-input>
        <span class="md-error">密码不能为空</span>
      </md-input-container>
      <md-button type="submit" class="md-raised md-primary">登录</md-button>
    </form>
  </div>
</template>

<script>
import { login } from './../../service/getData'
import store from 'store'
import {mapMutations, mapState} from 'vuex'
export default {
  data () {
    return {
      username: null,
      password: null
    }
  },
  computed: {
    ...mapState([
      'common'
    ])
  },
  mounted () {
    console.log(this.common.userInfo.username)
    if (!(this.common.userInfo.username === null)) {
      console.log(1)
      this.$router.push({name: 'homelist'})
    }
  },
  methods: {
    ...mapMutations([
      'RECORD_USER'
    ]),
    async submit () {
      try {
        let userInfo = await login({username: this.username, password: this.password})
        this.RECORD_USER(userInfo.payload)
        store.set('token', userInfo.payload.token)
        this.$router.push({name: 'homelist'})
      } catch (e) {
        console.log(e)
      }
    }
  }
}
</script>

<style scoped>
.container {
  padding: 20px
}
</style>
